<?php
/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2018/6/11
 * Time: 11:38
 */

namespace app\shell;

use app\Clearing\Clearing;
use app\common\Common;
use app\data\OrderData;
use app\data\ProxyDate;
use app\order\Order;
use think\Db;
use think\Log;

class Proxy extends Base
{

    public function index()
    {
        $proxy = new ProxyDate();
        $order = new Order();
        $clear = new Clearing('proxy');
        $province = Common::getTableValue('drh_admin_config', 'value', 'name', 'province');
        $municipal = Common::getTableValue('drh_admin_config', 'value', 'name', 'municipal');
        $res = $proxy->getProxy();
        $time = time();
        $start_time = strtotime(date('Y-m-d', $time - 3600 * 24));
        $end_time = $start_time + 3600 * 24;
        $info = $order->getOrderNum($start_time, $end_time);
        Db::startTrans();
        try {
            foreach ($res as $k => $v) {
                if ($v['lv'] == 3) {//1省 2市
                    continue;
                }
                $money = $this->getMoney($v['name'], $v['lv'], $info);//获取对应区域的总受益
                $clear->clearing([
                    'money' => $money,
                    'id' => $v['id'],
                    'proportion' => $v['lv'] == 1 ? $province : $municipal,
                    'lv'=>$v['lv']
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error($e);
        }
    }

    private function getMoney($name, $lv, $info)
    {
        $money = 0;
        $arr = ['province', 'municipal', 'district'];
        $value = $arr[$lv - 1];
        foreach ($info as $v) {
            if ($v[$value] == $name) {
                $money += $v['money'];
            }
        }
        return $money;
    }

    public function show()
    {
        $res = new Clearing('1234');
        echo $res->show();

    }
    public function timing_receiving(){
        $order =  Common::db_count("*","","drh_goods_order","settle_accounts=0 AND goods_status=1");
        $orderData = new OrderData();
        $clear = new Clearing('goods_order');
        foreach ($order as $k=>$v){
            $order[$k]['time'] = (int) date("j",bcsub(time(),$v['ship_time']));
            if($order[$k]['time']<8){
                unset($order[$k]);
            }
            $order_info = $orderData->getOrderInfo($v['order_num']);
            $clear->clearing([
                'order_num' => $v['order_num'],
                'time' => $v['ship_time'],
                'pay_status' => $v['pay_status'],
                'money' => $v['price'],
                'order_info' => $order_info
            ]);
            Common::db_upload("drh_goods_order","settle_accounts=1,order_end_time=".time().",goods_status=2,freight_method='7天自动收货' WHERE id={$v['id']}");
        }
    }
}